package com.flyqiu.form.core;

import com.flyqiu.form.api.col.FlyQiuStoreColTypeManage;
import com.flyqiu.form.api.spi.FlyQiuFormStoreInitialization;
import com.flyqiu.form.api.store.FlyQiuFormStoreManage;
import com.flyqiu.form.api.store.FlyQiuFormStoreService;
import org.apache.ibatis.transaction.TransactionFactory;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

public class DefaultFlyQiuFormImpl extends BaseFlyQiuForm {


    private final List<FlyQiuFormStoreInitialization> storeInitializations = new ArrayList<>();

    public DefaultFlyQiuFormImpl(DataSource dataSource) {
        this(dataSource, new SpringManagedTransactionFactory());

    }

    public DefaultFlyQiuFormImpl(DataSource dataSource, TransactionFactory transactionFactory) {
        ServiceLoader<FlyQiuFormStoreInitialization> load = ServiceLoader.load(FlyQiuFormStoreInitialization.class);
        for (FlyQiuFormStoreInitialization next : load) {
            storeInitializations.add(next);
        }
        this.context = DefaultFlyQiuFormContext.create(dataSource, transactionFactory, storeInitializations);
    }


    @Override
    protected void loadFormStores(FlyQiuFormStoreManage formStoreManage) {
        for (FlyQiuFormStoreInitialization initialization : storeInitializations) {
            FlyQiuFormStoreService storeService = initialization.initFormStore(context);
            formStoreManage.registerStore(storeService);
        }
    }

    @Override
    protected void loadFlyQiuStoreColType(FlyQiuStoreColTypeManage flyQiuStoreColTypeManage) {
        for (FlyQiuFormStoreInitialization initialization : storeInitializations) {
            flyQiuStoreColTypeManage.registerStoreColType(initialization);
        }
    }


}
